<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model="ruleForm.username"
          autocomplete="off"
          required
          placeholder="请输入用户名"
          maxlength="10"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
          required
          show-password
          placeholder="请输入密码"
        >
        </el-input>
      </el-form-item>
      <!-- 验证码div -->
      <div style="display: flex; height: 50px">
        <el-form-item label="验证码" prop="captchaCode">
          <el-input
            type="text"
            v-model="ruleForm.captchaCode"
            autocomplete="off"
            maxlength="5"
            placeholder="请输入五位数验证码"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- 验证码图片 -->
        <div>
          <img
            :src="ruleForm.captchaUrl"
            alt=""
            class="captcha-img"
            @click="refreshCode"
          />
        </div>
      </div>
      <label>
        <div class="form-remember" style="display: flex">
          <div class="space-white"></div>
          <el-checkbox
            v-model="ruleForm.rememberMe"
            style="margin-right: 40vh; flex: 1 1 auto"
            >保存账号信息</el-checkbox
          >
        </div>
      </label>

      <el-form-item>
        <el-button type="primary" @click="loginUser" class="login-button">
          登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { uuid } from "vue-uuid";
import UserApiRequest from "@/api/UserApiRequest";
const userApiRequest = new UserApiRequest();
export default {
  name: "loginFrom",
  props: {
    showLoginForm: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      }
      callback();
    };

    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      }
      callback();
    };
    return {
      // 登录表单信息
      ruleForm: {
        password: "",
        username: "",
        rememberMe: false,
        captchaUrl: "",
        captchaCode: "",
        captchaKey: uuid.v1().slice(20),
      },
      rules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        captchaCode: [{ validator: validateCode, trigger: "blur" }],
        username: [{ validator: validateUserName, trigger: "blur" }],
      },
    };
  },
  methods: {
    loginUser() {
      let data = {
        username: this.ruleForm.username.trim(),
        password: this.ruleForm.password.trim(),
        rememberMe: this.ruleForm.rememberMe,
        captchaCode: this.ruleForm.captchaCode,
        captchaKey: this.ruleForm.captchaKey,
      };
      if (data.username.split(" ").join("").length == 0) {
        this.$message({
          message: "用户名不能为空哦",
          type: "warning",
        });
        return;
      } else if (data.password.split(" ").join("").length == 0) {
        this.$message({
          message: "密码不能为空格哦",
          type: "warning",
        });
        return;
      }
      userApiRequest.loginUser(data).then((res) => {
        if (res.data.code === 201) {
          // 登录成功后获取到用户的头像 存放到vuex中  且 判断当前是否已经登录

          this.$message({
            message: "恭喜你,登录成功,欢迎来到zBlog",
            type: "success",
          });

          // 保存到本地中
          res.data.data.rememberMe = this.ruleForm.rememberMe;
          if (this.ruleForm.rememberMe) {
            this.$store.commit("setUserMsg", res.data.data);
            this.$store.commit("setUserPassword", data.password);
          } else {
            this.$store.commit("setUserMsg", res.data.data);
          }
          // 设置过期时间 ， token ， 以及 vuex中的用户数据
          localStorage.setItem(
            "tokenTime",
            new Date().getTime() + 7 * 24 * 3600 * 1000
          );
          localStorage.setItem("auth", res.headers.authorization);
          localStorage.setItem("store", JSON.stringify(this.$store.state));

          this.$refs.ruleForm.resetFields();
          // 关闭弹窗组件;
          this.$emit("closeLoginWindow", false);
          // 如果保存了点了remember 进行保存信息
          if (data.rememberMe) {
            this.ruleForm.username = data.username;
            this.ruleForm.password = data.password;
            this.ruleForm.rememberMe = data.rememberMe;
          }
          this.$router.push("/userCenter");
        }
        if (res.data.code === -410) {
          this.$message({
            message: "用户名或者密码不正确哦! 请再检查一下",
            type: "warning",
          });
          this.refreshCode();
          return;
        }
        if (res.data.code === -411) {
          this.$message({
            message: "验证码输入不正确哦! 请再检查一下",
            type: "warning",
          });
          this.refreshCode();
          return;
        }
        if (res.data.code === -412) {
          this.$message({
            message: "验证码已过期请重新获取再输入",
            type: "warning",
          });
          this.refreshCode();
          return;
        }
      });
    },

    // 刷新验证码
    async refreshCode() {
      userApiRequest
        .getCaptchaImg({ captchaKey: this.ruleForm.captchaKey })
        .then((res) => {
          this.ruleForm.captchaUrl = window.URL.createObjectURL(res);
        });
    },
  },
  // 获取验证码
  async mounted() {
    let data;
    userApiRequest
      .getCaptchaImg({ captchaKey: this.ruleForm.captchaKey })
      .then((res) => {
        data = res;
        this.ruleForm.captchaUrl = window.URL.createObjectURL(res);
      });
    this.$nextTick(() => {
      this.ruleForm.captchaUrl = data;
    });
    // 页面加载时将保存的数据进行放入到表单中
    let userInfo = JSON.parse(localStorage.getItem("store")).userInfo;
    if (userInfo) {
      if (userInfo.remember) {
        this.ruleForm.username = userInfo.username;
        this.ruleForm.password = userInfo.password;
      }
      this.ruleForm.rememberMe = userInfo.remember;
    }
  },

  watch: {
    showLoginForm: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.refreshCode();
        } else {
          this.ruleForm.captchaUrl = "";
        }
      },
    },
  },
};
</script>

<style scoped lang="scss">
.form-remember {
  margin-bottom: 15px;
  text-align: right;
}
.captcha-img {
  margin-left: 10px;
}
.login-button {
  width: 100%;
  display: block;
  font-size: 17px;
  color: #fff;
}
.space-white {
  width: 400px;
  margin-top: 10px;
  margin-left: 50%;
}
</style>
